package dou.net.protocol;

import dou.net.socket.InvalidProtocolException;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 所有的协议管理类
 * @author wizardc
 */
public class ProtocolManager
{
    private static ProtocolManager _instance;

    /**
     * 获取该类全局唯一的实例
     * @return 该类全局唯一的实例
     */
    public static synchronized ProtocolManager getInstance()
    {
        if(_instance == null)
        {
            _instance = new ProtocolManager();
        }
        return _instance;
    }

    private ConcurrentMap<Integer, IProtocol> _protocolMap;

    /**
     * 构造函数
     */
    private ProtocolManager()
    {
        _protocolMap = new ConcurrentHashMap<Integer, IProtocol>();
    }

    /**
     * 注册一个协议对象
     * @param protocol 要注册的协议对象
     */
    public void registerProtocol(IProtocol protocol) throws InvalidProtocolException
    {
        List<Integer> msgIDList = protocol.msgIDList();
        for (int msgID : msgIDList)
        {
            if (_protocolMap.containsKey(msgID))
            {
                throw new InvalidProtocolException("MsgID \"" + msgID + "\" has already existed!");
            }
            _protocolMap.put(msgID, protocol);
        }
    }

    /**
     * 获取一个协议对象
     * @param msgID 消息 ID
     * @return 对应的协议对象
     */
    public synchronized IProtocol getProtocol(int msgID)
    {
        if(_protocolMap.containsKey(msgID))
        {
            return _protocolMap.get(msgID);
        }
        return null;
    }
}
